package levy.sum.chapter1.client;

import java.util.Scanner;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class Client {

	private String remoteHost;
	private int remotePort;

	public Client(String remoteHost, int remotePort) {
		super();
		this.remoteHost = remoteHost;
		this.remotePort = remotePort;
	}

	public static void main(String[] args) {
		new Client("localhost", 9999).start();
	}

	public void start() {
		EventLoopGroup worker = new NioEventLoopGroup();

		Bootstrap bootstrap = new Bootstrap();

		bootstrap.group(worker);
		bootstrap.channel(NioSocketChannel.class);
		bootstrap.handler(new ClientIniterHandler());

		Scanner scanner = new Scanner(System.in);

		try {
			Channel channel = bootstrap.connect(remoteHost, remotePort).sync()
					.channel();
			while (true) {
				System.out.println("input:");
				String input = scanner.nextLine();
				if ("quit!".equalsIgnoreCase(input)) {
					scanner.close();
					break;
				}
				channel.writeAndFlush(input);
			}

			/** 同步等待关闭 */
			channel.closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			worker.shutdownGracefully();
			scanner.close();
		}
	}
}
